package com.album.activity;

 
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.album.R;
import com.album.activity.base.BaseActivity;
import com.album.utils.CommonUtil;
import com.album.utils.MyLog;

import dalvik.system.VMRuntime;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;

import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;

import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class CoOfImageListActivity extends Activity {
	private GridView gridView;
	public static TextView countText;
	private Button btnBack;
	public static Button btnReset, btnGenerate;
	private BitmapFactory.Options options, options2;
	public static int maxCount = 12;
	public static int displayWidth, displayHeight;
	public static List<Bitmap> resizeBitmaps = new ArrayList<Bitmap>();
	private LinearLayout imageLayout;
	private String filePath;
	private Bitmap bitmap;
	private HashMap<String, SoftReference<Bitmap>> tempMap;
	private SimpleCursorAdapter cursorAdapter;
	private Cursor imageCursor;
	public static List<Bitmap> selectedBitmapList = new ArrayList<Bitmap>(); 
	private boolean isGenerate = false;// 判断是不是跳转到生成界面，如果不是的话，不清空selectedBitmapList。
	private HorizontalScrollView scrollView;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.image_list);  
		// 文件夹路径
		filePath = getIntent().getExtras().getString("filePath");

		imageLayout = (LinearLayout) findViewById(R.id.imageLayout);
		gridView = (GridView) findViewById(R.id.gridView);
		countText = (TextView) findViewById(R.id.countText);
		btnGenerate = (Button) findViewById(R.id.btnGenerate);
		btnReset = (Button) findViewById(R.id.btnReset);
		btnBack = (Button) findViewById(R.id.btnBack);
		scrollView = (HorizontalScrollView) findViewById(R.id.footScrollView);
		options = new BitmapFactory.Options();
		options.inSampleSize = 100;
		setAdapter();
	}
	
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
					//Log.w("---------------", "不断执行"+msg.what);
					scrollView.smoothScrollBy(1500, 0);
					//scrollView.scrollBy(150, 0);
			}
	};
	private Runnable runnable = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			 
			Message msg = handler.obtainMessage();
			 //msg.what = 1;
			 handler.sendMessage(msg);
		}  
		
	};

	@Override
	protected void onStart() {
		// 没选择图片时，重置和生成按钮不可以点击
		btnGenerate.setEnabled(false);
		if (selectedBitmapList != null && selectedBitmapList.size() > 0 && resizeBitmaps != null
				&& resizeBitmaps.size() > 0) {
			View selectedView;
			btnReset.setEnabled(true);
			btnGenerate.setEnabled(true);
			for (int i = 0, l = resizeBitmaps.size(); i < l; i++) {
				selectedView = getLayoutInflater().inflate(R.layout.selected_imageview, null);
				LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(130, 110);
				layoutParams.setMargins(0, 0, 7, 0);
				selectedView.setLayoutParams(layoutParams);
				ImageView selectedImageView = (ImageView) selectedView.findViewById(R.id.selectImageView);
				ImageView deleteImageView = (ImageView) selectedView.findViewById(R.id.deleteImageView);
				selectedImageView.setImageBitmap(selectedBitmapList.get(i));
				selectedView.setTag(resizeBitmaps.get(i));
				deleteImageView.setTag(selectedView);
				deleteImageView.setOnTouchListener(imageListener);
				imageLayout.addView(selectedView);
			}
		} else {
			btnReset.setEnabled(false);
		}
		displayHeight = getWindowManager().getDefaultDisplay().getHeight();
		displayWidth = getWindowManager().getDefaultDisplay().getWidth();
		countText.setText(String.format(getString(R.string.error_title), --maxCount));
		
		gridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				handler.post(runnable);

				if (maxCount > 0) {
					// 选择了图片，这时候重置和生成按钮可以点击。
					btnGenerate.setEnabled(true);
					btnReset.setEnabled(true);
					try {
						// 更改还可以选择的图片数目
						countText.setText(String.format(getString(R.string.error_title), --maxCount));
						View selectedView = getLayoutInflater().inflate(R.layout.selected_imageview, null);
						LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(130, 110);
						layoutParams.setMargins(0, 0, 7, 0);
						selectedView.setLayoutParams(layoutParams);
						ImageView selectedImageView = (ImageView) selectedView.findViewById(R.id.selectImageView);
						ImageView deleteImageView = (ImageView) selectedView.findViewById(R.id.deleteImageView);
						options2 = new BitmapFactory.Options();
						options2.inJustDecodeBounds = true;
						imageCursor.moveToPosition(position);
						BitmapFactory.decodeFile(imageCursor.getString(imageCursor.getColumnIndex("_data")), options2);						
						Log.d("=============", "wwww:"+options2.outHeight+"=====hhhh:"+options2.outWidth);						
						if (options2.outHeight < 1000 && options2.outWidth < 1000) {
							options2.inSampleSize = 1;
						} else {
							options2.inSampleSize = computeInitialSampleSize(options2, -1, 500 * 500);
						}
						options2.inJustDecodeBounds = false;
						Bitmap tmpBitmap = BitmapFactory.decodeFile(imageCursor.getString(imageCursor
								.getColumnIndex("_data")), options2); 
						Log.i("width+height", "inSample:"+options2.inSampleSize+"width=" + tmpBitmap.getWidth() + "height=" + tmpBitmap.getHeight());
						if (tmpBitmap.getWidth() > 480 && tmpBitmap.getHeight() > 480) {
							Bitmap tmpResizeBitmap = tmpBitmap;
							tmpBitmap = CommonUtil.createImage(tmpResizeBitmap, 480, 480, true);
							if (tmpResizeBitmap != null && tmpResizeBitmap.isRecycled() == false) {
								tmpResizeBitmap.recycle();
								tmpResizeBitmap = null;
							}
						}
						Log.i("高与宽", "宽=" + tmpBitmap.getWidth() + "高=" + tmpBitmap.getHeight());						
						resizeBitmaps.add(tmpBitmap);
						selectedView.setTag(tmpBitmap);						
						
						view.setDrawingCacheEnabled(true);
						bitmap = Bitmap.createScaledBitmap(view.getDrawingCache(), 125, 105, true);						
						selectedImageView.setImageBitmap(bitmap);
						selectedImageView.setTag(bitmap);
						deleteImageView.setTag(selectedView);
						deleteImageView.setOnTouchListener(imageListener);
						imageLayout.addView(selectedView);
						// 选择图片后，往左移一位
						/*scrollView.smoothScrollBy(150, 0);
						scrollView.computeScroll();
						Log.i("dsm", "滚动布局宽度>>>>>>>>>"+scrollView.getWidth()+"滚动布局的高度>>>>>>>>"+scrollView.getHeight()+"滚动布局滚动的进度>>>>>"+scrollView.getScrollX());*/
						/*scrollView.scrollTo(scrollView.getWidth(), 0);
						if (scrollView.getScrollX()<100) {
							Log.w("dsm", "移动未能达到125所以补助移动");
							
							scrollView.scrollBy(67, 0);
						}*/
						
						
						selectedBitmapList.add(bitmap);
						
						tmpBitmap = null;
						options2 = null;						
					} catch (OutOfMemoryError e) {
						Toast.makeText(CoOfImageListActivity.this, getString(R.string.home_camear),
								Toast.LENGTH_SHORT).show();
						e.printStackTrace();
					} catch (IndexOutOfBoundsException e) {
						e.printStackTrace();
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {
					Toast.makeText(CoOfImageListActivity.this, getString(R.string.home_cancel), Toast.LENGTH_SHORT).show();
				}
			}
		});
		// 重置按钮，删除已选择的图片
		btnReset.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				btnGenerate.setEnabled(false);
				btnReset.setEnabled(false);
				if (resizeBitmaps != null) {
					for (int i = 0, l = resizeBitmaps.size(); i < l; i++) {
						if (resizeBitmaps.get(i) != null && !resizeBitmaps.get(i).isRecycled()) {
							resizeBitmaps.get(i).recycle();
						}
					}
					resizeBitmaps.clear();
				}
				imageLayout.removeAllViews();
				if (selectedBitmapList != null && selectedBitmapList.size() > 0) {
					for (int i = 0, l = selectedBitmapList.size(); i < l; i++) {
						if (selectedBitmapList.get(i) != null && !selectedBitmapList.get(i).isRecycled()) {
							selectedBitmapList.get(i).recycle();
						}
					}
					selectedBitmapList.clear();
				}
				maxCount = 12;
				countText.setText(String.format(getString(R.string.home_refresh), maxCount));
				clearBitmap();
			}
		});
		// 返回选择相册界面
		btnBack.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				backEvent(ImageFolderListActivity.class, null);
			}
		});
		
		// 跳转到图片生成界面
		btnGenerate.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (resizeBitmaps != null) {
					if (resizeBitmaps.size() >= 2) {
						maxCount = 12;
						// 把选择的图片处理一下
						imageLayout.removeAllViews();
						imageLayout.setVisibility(View.GONE);
						// 把已经存储的已选择图片的缩略图回收
						if (selectedBitmapList != null && selectedBitmapList.size() > 0) {
							for (int i = 0, l = selectedBitmapList.size(); i < l; i++) {
								if (selectedBitmapList.get(i) != null && !selectedBitmapList.get(i).isRecycled()) {
									selectedBitmapList.get(i).recycle();
								}
							}
							selectedBitmapList.clear();
						}
						isGenerate = true;
						backEvent(HomeActivity.class, filePath);
					} else if (resizeBitmaps.size() == 1) {
						Toast.makeText(CoOfImageListActivity.this, "image_min", Toast.LENGTH_SHORT)
								.show();
					}
				}
			}
		});
		System.gc();
		super.onStart();
	}

	// 删除图片的点击事件
	private OnTouchListener imageListener = new OnTouchListener() {
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			View tempView = (View) v.getTag();
			// 删除已经添加到图片
			resizeBitmaps.remove(tempView.getTag());
			imageLayout.removeView(tempView);
			selectedBitmapList.remove(tempView.findViewById(R.id.selectImageView).getTag());
			maxCount = 12 - imageLayout.getChildCount();
			countText.setText(String.format(getString(R.string.home_wangpang), maxCount));
			return true;
		}
	};

	// 回收图片
	private void clearBitmap() {
		if (resizeBitmaps != null && resizeBitmaps.size() > 0) {
			for (int i = 0, l = resizeBitmaps.size(); i < l; i++) {
				if (resizeBitmaps.get(i) != null && !resizeBitmaps.get(i).isRecycled()) {
					resizeBitmaps.get(i).recycle();
				}
			}
			resizeBitmaps.clear();
		}
	}

	// 所有离开当前页面事件的处理
	private void backEvent(Class<?> cls, String extraString) {
		VMRuntime.getRuntime().gcSoftReferences();
		Intent intent = new Intent(CoOfImageListActivity.this, cls);
		if (extraString != null) {
			intent.putExtra("filePath", filePath);
		}
		CoOfImageListActivity.this.startActivity(intent);
		if (gridView != null) {
			gridView.setVisibility(View.GONE);
			gridView = null;
		}
		if (imageCursor != null && !imageCursor.isClosed()) {
			imageCursor.close();
		}
		// 如果是跳转到图片生成界面，清空selectedBitmapList。
		if (isGenerate) {
			if (selectedBitmapList != null && selectedBitmapList.size() > 0) {
				for (int i = 0, l = selectedBitmapList.size(); i < l; i++) {
					if (selectedBitmapList.get(i) != null && !selectedBitmapList.get(i).isRecycled()) {
						selectedBitmapList.get(i).recycle();
					}
				}
				selectedBitmapList.clear();
			}
		}
		finish();
	}

	@Override
	protected void onPause() { 
		super.onPause();
	}

	@Override
	protected void onResume() { 
		super.onResume();
	}

	// 返回键跳转到模式选择界面
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			backEvent(ImageFolderListActivity.class, null);
		}
		return super.onKeyDown(keyCode, event);
	}

	private void setAdapter() {
		if (imageCursor != null && !imageCursor.isClosed()) {
			imageCursor.close();
		}
		imageCursor = getCursor();
		if (imageCursor != null && imageCursor.getCount() > 0) {
			imageCursor.moveToFirst();
			cursorAdapter = new MyCursorAdapter(this, R.layout.image_item, imageCursor,
					new String[] { "_data", "_ID" }, new int[] { R.id.image });
			gridView.setAdapter(cursorAdapter);
		}
	}

	private int computeInitialSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
		double w = options.outWidth;
		double h = options.outHeight;
		int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
		int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(Math.floor(w / minSideLength), Math.floor(h
				/ minSideLength));
		if (upperBound < lowerBound) {
			return lowerBound;
		}
		if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
			return 1;
		} else if (minSideLength == -1) {
			return lowerBound;
		} else {
			return upperBound;
		}
	}

	private Cursor getCursor() {
		Uri originalUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
		ContentResolver cr = getContentResolver();
		// "_id DESC"的作用是使新拍摄的照片可以在前面显示
		imageCursor = cr.query(originalUri, null, "_data like '%" + filePath + "%'", null, "_id DESC");
		String[] strings = imageCursor.getColumnNames();
		for (int i = 0; i < strings.length; i++) {
			MyLog.debug(getClass(), "YYYYYYYYYYYYYYYYYYYYY:"+strings[i]);
		}
		return imageCursor;
	}

	class MyCursorAdapter extends SimpleCursorAdapter {
		public MyCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
			super(context, layout, c, from, to);
			tempMap = new HashMap<String, SoftReference<Bitmap>>();

		}

		@Override
		public void bindView(View view, Context context, Cursor cursor) {
			if (view != null) {
				ImageView v = (ImageView) view.findViewById(R.id.image);
				String value = cursor.getString(cursor.getColumnIndex("_data"));
				try {
					v.setImageBitmap(null);
					if (tempMap != null && tempMap.containsKey(value) && tempMap.get(value).get() != null
							&& !tempMap.get(value).get().isRecycled()) { 
						v.setImageBitmap(tempMap.get(value).get());
					} else {
						int id = cursor.getInt(cursor.getColumnIndex("_ID"));
						bitmap = MediaStore.Images.Thumbnails.getThumbnail(getContentResolver(), id,
								MediaStore.Images.Thumbnails.MICRO_KIND, options);
						Log.i("高和宽", bitmap.getHeight() + "," + bitmap.getWidth() + "");
						tempMap.put(value, new SoftReference<Bitmap>(bitmap));
						v.setImageBitmap(bitmap);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				return;
			}
			super.bindView(view, context, cursor);
		}
	}

	class BackBroadCastReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) { 
			CoOfImageListActivity.this.finish();
		}
	}
 
}
